package com.wxw.BaseLibrary.http.soap;

import android.util.Log;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.json.JSONStringer;

import java.net.HttpURLConnection;
import java.util.Map;
import java.util.Set;

/**
 * Created by david on 2016/5/11.
 */
public class PostSoapExecutor implements SoapExecutor {
    private static PostSoapExecutor _INSTANCE;

    private PostSoapExecutor(){

    }

    public static PostSoapExecutor getInstance() {
        if (_INSTANCE == null) {
            _INSTANCE = new PostSoapExecutor();
        }
        return _INSTANCE;
    }

    @Override
    public <T> SoapResponse<T> executeRequest(Request<T> request) {
        String url = request.url();
        Map<String, Object> params = request.getParams();
        HttpPost httpPost = new HttpPost(url);
        int StatusCode=0;
        long startTime = System.currentTimeMillis();
        Exception exception = null;
        byte[] body = null;
        T result = null;

        if (request.getHeaders() != null && request.getHeaders().size()>0) {
            Set<String> keys = request.getHeaders().keySet();
            for (String key : keys) {
                httpPost.setHeader(key, request.getHeaders().get(key));
            }
        }
        if (!"".equals(request.getAccept())) {
            httpPost.setHeader("Accept", request.getAccept());
        }
        if (!"".equals(request.getContentType())) {
            httpPost.setHeader("Content-type", request.getContentType());
        }
//        } else {
//            httpPost.setHeader("Accept", "application/json");
//            httpPost.setHeader("Content-type", "application/json");
//        }

        try {
            // 设置需调用WebService接口需要传入的两个参数mobileCode、userId
            if (params != null && params.size() > 0) {
                JSONStringer spa = new JSONStringer().object();
                Set<String> keys = params.keySet();
                for (String s : keys) {
                    spa.key(s).value(params.get(s));
                }
                spa.endObject();
                httpPost.setEntity(new StringEntity(spa.toString(), "utf-8"));
            }
            // 向WCF服务发送请求
            DefaultHttpClient httpClient = new DefaultHttpClient();
            httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 20000);
            httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 300000);
            HttpResponse response = httpClient.execute(httpPost);

            StatusCode = response.getStatusLine().getStatusCode();
            // 判断是否成功
            if (StatusCode == HttpURLConnection.HTTP_OK){
                body = SoapResponse.readResponseBody(response.getEntity().getContent());
                result = request.parseResponse(url, body);
            }else {
                body = response.getEntity().toString().getBytes("utf-8");
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            exception = e;
            e.printStackTrace();
            Log.e("PSE", e.getMessage());
        }
        long endTime = System.currentTimeMillis();

        return new SoapResponse(url, RequestMethod.GET, request.getHeaders(),StatusCode, body, result,
                request.getTag(),endTime-startTime, exception);
    }
}
